<!-- 内容管理 -->
<template>
    <!-- <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="内容管理" name="1"></el-tab-pane>
    <el-tab-pane label="内容审核" name="2"></el-tab-pane>
    <el-tab-pane label="审核记录" name="3"></el-tab-pane>
  </el-tabs> -->
    <div v-if="activeName=='1'">
        <el-button  type="primary" @click="add('add')" style="margin-bottom: 10px;">新增内容</el-button>
        <el-button  type="primary" @click="BatchDelet" style="margin-bottom: 10px;">批量删除</el-button>
    </div>
    <div style="display: flex;justify-content: space-between;">
        <div style="width: 15%;">
            <el-tree :data="data.treeData" :props="defaultProps" node-key="id" :current-node-key="defaultCheckedKeys" default-expand-all highlight-current @node-click="handleNodeClick" ref="treeRef" style="height:750px;overflow:auto;" />
        </div>
        <div style="width: 84%;">
            <div style="margin-bottom: 10px;">
                <el-input v-model="titleValue" clearable style="width: 240px;margin-right:10px;" placeholder="请输入标题查询" />
                <el-button type="primary" @click="getList()">查询</el-button>
            </div>
            <el-table :data="data.tableData" row-key="id" table-layout="auto" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column label="模板类型" width="200" align="center">
                    <template #default="scope">
                        <div v-if="scope.row.templateType == 1">通用模板（列表）</div>
                        <div v-if="scope.row.templateType == 2">通用模板（全内容）</div>
                        <div v-if="scope.row.templateType == 3">通用模板（图文）</div>
                        <div v-if="scope.row.templateType == 4">通用模板（图片）</div>
                        <div v-if="scope.row.templateType == 5">通用模板（视频）</div>
                        <div v-if="scope.row.templateType == 6">鞍钢楷模专属模版</div>
                        <div v-if="scope.row.templateType == 7">董事集团会专属模版</div>
                        <div v-if="scope.row.templateType == 8">主要荣誉专属模版</div>
                        <div v-if="scope.row.templateType == 9">集团高管专属模板</div>
                        <div v-if="scope.row.templateType == 10">鞍钢出版物专属模板</div>
                        <div v-if="scope.row.templateType == 11">时政要闻专属模板</div>
                        <div v-if="scope.row.templateType == 12">股票信息专属模板</div>
                        <div v-if="scope.row.templateType == 13">报告专属模板</div>
                        <div v-if="scope.row.templateType == 14">产品专属模板</div>
                        <div v-if="scope.row.templateType == 15">文化专属模板</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="[7,8,9].includes(columnType)" prop="title" label="名称" width="" align="center"  />
                <el-table-column v-if="[7,9].includes(columnType)" prop="linkTitle" label="职务" width="" align="center"  />
                <el-table-column prop="title" label="标题名称" width="" align="left" v-if="[1,6,10,11].includes(columnType)" />
                <!-- <el-table-column label="内容" width="200" align="center" show-overflow-tooltip v-if="[1,2,10,11].includes(columnType)">
                    <template #default="scope">
                        <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" alt="" style="width: 100px;height: 100px;">
                        <div v-html="scope.row.contentText"></div>
                    </template>
                </el-table-column> -->
                <el-table-column prop="linkTitle" label="文字描述" width="300" show-overflow-tooltip align="center" v-if="[3,4,5,13].includes(columnType)" />
                <el-table-column prop="imageUrl" label="图片" width="" align="center" v-if="[3,4,7,8,9].includes(columnType)">
                    <template #default="scope">
                        <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" alt="" style="width: 100px;height: 100px;">
                    </template>
                </el-table-column>
                <el-table-column prop="imageUrl" label="视频" width="" align="center" v-if="[5].includes(columnType)">
                    <template #default="scope">
                        <video v-if="scope.row.imageUrl" controls style="width: 100px;height: 100px;">
                            <source :src="scope.row.imageUrl" type="video/mp4">
                        </video>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="发布状态" width="100px" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status === 1" type="success">已发布</el-tag>
                        <el-tag v-if="scope.row.status === 0" type="danger">未发布</el-tag>
                    </template>
                </el-table-column>
                <el-table-column v-if="activeName=='2'" prop="agApprove.creatorName" label="提交人" width="" />
                <el-table-column v-if="activeName=='2'" prop="agApprove.createTime" label="提交时间" width="" />
                <el-table-column prop="source" label="内容来源" width="100px" align="center" />
                <el-table-column prop="publishTime" label="发布时间" width="140px" align="center" />
                <el-table-column prop="cancellationTime" label="撤销时间" width="140px" align="center" />
                <el-table-column prop="createTime" label="创建时间" width="140px" align="center" />
                <el-table-column prop="updateTime" label="更新时间" width="140px" align="center" />
                <el-table-column prop="creator" label="创建人" width="100px" align="center" />
                <el-table-column prop="updater" label="更新人" width="100px" align="center" />
                <el-table-column prop="deleted" label="删除标识" width="100px" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.deleted === 0">正常</span>
                        <span v-if="scope.row.deleted === 1">已删除</span>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序" width="100px" align="center" />
                <el-table-column prop="" label="操作" width="150" fixed="right" align="center">
                    <template #default="scope">
                        <div style="display: flex;">
                            <div v-if="activeName=='1'" style="display: flex;">
                                <el-button  type="primary" @click="add('edit',scope.row)">编辑</el-button>
                                <el-button  type="danger" @click="deleteColumn(scope.row)">删除</el-button>
                                <el-button v-if="[1,2,11].includes(scope.row.templateType)"   @click="preview(scope.row)">预览</el-button>
                                <el-button v-if="scope.row.status === 0" type="success" plain @click="openTimeDialog(scope.row,1)">发布</el-button>
                                <el-button v-if="scope.row.status === 1" type="danger" plain @click="openTimeDialog(scope.row,0)">撤销</el-button>
                                <!-- <el-button v-if="['1','5'].includes(scope.row.approveState)" type="primary" @click="check(scope.row)">提交审核</el-button> -->
                            </div>
                            <div v-if="activeName=='2'">
                                <el-button type="success" plain @click="examine('4',scope.row)">通过</el-button>
                                <el-button type="danger" plain @click="reject(scope.row)">驳回</el-button>
                            </div>
                            <!-- <el-button type="text" @click="preview(scope.row)" style="margin-left:15px;">预览</el-button> -->
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getList" @current-change="getList" style="margin-top: 20px;display:flex;justify-content: flex-end;" />
        </div>
    </div>
    <dialogForm ref="dialogFormRef" @resetList="getList"></dialogForm>

    <el-dialog v-model="rejectShow" title="驳回意见" @close="cancel" width="30%">
        <el-input v-model="textarea" :rows="5" type="textarea" />
        <template #footer>
            <el-button type="primary" @click="examine('5')">确定</el-button>
        </template>
    </el-dialog>

    <el-dialog v-model="timeDialog" :title="timeTitle" width="500">
        <el-radio-group v-model="timeType">
            <el-radio :value="0" border>立即{{timeTitle}}</el-radio>
            <el-radio :value="1" border>定时{{timeTitle}}</el-radio>
        </el-radio-group>
        <div style="margin-top: 10px;">
            <el-date-picker v-if="timeType==1" v-model="publishTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="timeDialogOk">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { selectContent, deleteContent, saveContent, listColumn, submitReviewColumn, approveColumn,promptlyStatus } from '@/api/allApi'
import dialogForm from './dialogForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { treeTitle } from '@/utils/myMethod' //工具类
import { useRouter } from 'vue-router'

const dialogFormRef = ref()
const userInfo = JSON.parse(localStorage.getItem('userInfo'))

onMounted(() => {
	getTree()
})

const defaultProps = { children: 'children', label: 'label' }
const defaultCheckedKeys = ref(0)
const treeRef = ref<InstanceType<typeof ElTree>>()
//获取树
const getTree = () => {
	listColumn({
		websiteId: Number(localStorage.getItem('WebsiteId')),
		pageNum: 1,
		pageSize: 1000
	}).then((res: any) => {
		if (res.code === 0) {
			//用push的方法可以解决reactive定义的数组不能直接被赋值的问题，也可以选择包一层，或者用ref定义.value是可以的
			data.treeData = treeTitle(res.data.list, 'name')
			const recursion = (item: any) => {
				if (item.children && item.children.length > 0) {
					recursion(item.children[0])
				} else {
					nextTick(() => {
						defaultCheckedKeys.value = item.id
					})
					return handleNodeClick(item)
				}
			}
			recursion(data.treeData[0])
		} else {
			ElMessage.success(res.msg)
		}
	})
}
const columnId = ref('')
const columnType = ref('')
const contentPermission = ref('')
//树选中
const handleNodeClick = val => {
	if (val.children && val.children.length > 0) {
	} else {
		columnId.value = val.id
		columnType.value = val.templateType
        // 不需要按钮权限了
		// contentPermission.value = val.agCategoryPermission && val.agCategoryPermission.contentPermission ? val.agCategoryPermission.contentPermission : ''
		titleValue.value=''
        getList()
	}
}

const pageNum = ref(1) //第几页
const pageSize = ref(10) //每页多少条
const total = ref(0) //总条数
const data = reactive({
	tableData: [],
	treeData: []
})
const titleValue = ref('')
const getList = () => {
	let param = {
		websiteId: Number(localStorage.getItem('WebsiteId')), //网站id 1：鞍钢官网 2：博物馆
		templateType: columnType.value,
		pageNum: pageNum.value,
		pageSize: pageSize.value,
		id: columnId.value,
        title: titleValue.value
	}
	if (activeName.value == '2') {
		param.approveState = '2'
	} else if (activeName.value == '3') {
		param.approveState = '4'
	}
	console.log(activeName.value, 'activeName.value')

	selectContent(param).then((res: any) => {
		if (res.code === 0) {
			data.tableData = []
			res.data.list.forEach((item: any) => {
				data.tableData.push({
					...item,
					contentText: new DOMParser().parseFromString(item.content, 'text/html').body.textContent
				})
			})
			total.value = res.data.total
		} else {
			ElMessage.success(res.msg)
		}
	})
}

//操作标签页
const activeName = ref('1')
const handleClick = (val: any) => {
	activeName.value = val.props.name
	getList()
}

//表格勾选
const popdata = ref([])
const handleSelectionChange = e => {
	popdata.value = e
}
//批量删除
const BatchDelet = () => {
	let data = popdata.value
	deleteContent(data).then((res: any) => {
		if (res.code === 0) {
			getList()
		} else {
			ElMessage.success(res.msg)
		}
	})
}
//发布撤消
// const switchChange = (row: any,type:number) => {
// 	saveContent([
// 		{
// 			id: row.id,
// 			status: type,
// 			templateType: row.templateType,
// 			linkTitle: row.linkTitle,
// 			websiteId: Number(localStorage.getItem('WebsiteId')) //网站id
// 		}
// 	]).then(res => {
// 		if (res.code === 0) {
// 			ElMessage.success('操作成功')
// 			getList()
// 		} else {
// 		}
// 	})
// }
//新增
const add = (type: string, row: any) => {
	dialogFormRef.value.init(type, row)
}
//单个删除
const deleteColumn = (row: any) => {
	ElMessageBox.confirm(`是否删除？`, '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		deleteContent([row]).then((res: any) => {
			if (res.code === 0) {
				ElMessage.success('已删除')
				getList()
			} else {
				ElMessage.error(res.msg)
			}
		})
	})
}
//预览
const router = useRouter()
const preview = (row: any) => {
	// 在新标签页中打开
	const routeData = router.resolve({
		path: `/preview/Details`,
		query: {
			contentId: row.id,
			sonId: row.categoryId,
		}
	})
	window.open(routeData.href, '_blank')
	// window.open(`http://192.168.0.15:8080/subpage/index?id=${row.parentId}&sonId=${row.categoryId}&contentId=${row.id}`)
}
//提交审核
const check = (row: any) => {
	submitReviewColumn({
		businessType: '2',
		businessId: row.id
	}).then(res => {
		if (res.code === 0) {
			getList()
			ElMessage.success('提交成功')
		} else {
			ElMessage.error(res.msg)
		}
	})
}

const rejectShow = ref(false)
const textarea = ref('')
const rowId = ref('')
const reject = (row: any) => {
	rejectShow.value = true
	rowId.value = row.agApprove.id
}
const cancel = () => {
	rejectShow.value = false
	textarea.value = ''
}
const examine = (status: string, row: any) => {
	let params = {}
	if (status === '4') {
		params = {
			id: row.agApprove.id,
			approveState: status
		}
	} else if (status === '5') {
		params = {
			id: rowId.value,
			approveState: status,
			approveReason: textarea.value
		}
	}
	approveColumn(params).then(res => {
		if (res.code === 0) {
			ElMessage.success('审批完成')
			getList()
			cancel()
		} else {
			ElMessage.error(res.msg)
		}
	})
}

const timeDialog = ref(false)
const timeTitle = ref('发布')
const timeType = ref(0)
const timeDialogRow = reactive({})
const publishTime = ref('')

const openTimeDialog = (row: any, type: number) => {
	// timeDialog.value = true
	// publishTime.value = row.publishTime
	// Object.assign(timeDialogRow, row)
	// if (type == 1) {
	// 	timeTitle.value = '发布'
	// } else if (type == 0) {
	// 	timeTitle.value = '撤销'
	// }
    promptlyStatus({
        id: row.id,
        status: type,
    }).then(res=>{
        if (res.code === 0) {
			ElMessage.success('操作成功')
			getList()
		} else {
			ElMessage.error(res.msg)
		}
    })
}
const timeDialogOk = () => {
	let obj = {
		id: timeDialogRow.id,
		templateType: timeDialogRow.templateType,
		linkTitle: timeDialogRow.linkTitle,
		publishTime: publishTime.value,
		publishType: timeTitle.value == '发布' ? 0 : 1,
		websiteId: Number(localStorage.getItem('WebsiteId')) //网站id
	}
	if (timeType.value == 0) {
		obj.status = timeTitle.value == '发布' ? 1 : 0
	}
	saveContent([obj]).then(res => {
		if (res.code === 0) {
			timeDialog.value = false
			ElMessage.success('操作成功')
			getList()
		} else {
		}
	})
}
</script>
  
<style lang="scss" scoped>
//搭配el-table里的table-layout="auto"属性，再让每一列里的width为空即可展现出适应表格内容的列宽
:deep(.el-table .cell) {
	width: max-content;
	display: inline-block;
}
// .main-head-item {
// 	align-items: center;
// 	justify-content: center;
// 	width: 174px;
// 	height: 48px;
// 	background-color: #e9ecf1;
// 	border: 1px solid #fff;
// 	box-sizing: border-box;
// 	display: flex;
// 	cursor: pointer;
// }
// .tabbox {
// 	display: flex;
// }
// .active {
// 	background-color: rgb(29, 135, 228);
// }
</style>
  